/*
 * SyncResource.java
 *
 * Created on April 12, 2007, 1:39 PM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package org.atomojo.auth.service.app;

import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.UUID;
import java.util.logging.Level;
import org.atomojo.app.client.XMLRepresentationParser;
import org.atomojo.auth.service.db.AuthDB;
import org.atomojo.auth.service.db.Role;
import org.atomojo.auth.service.db.User;
import org.atomojo.auth.service.db.XML;
import org.infoset.xml.Document;
import org.infoset.xml.Element;
import org.infoset.xml.util.DocumentDestination;
import org.restlet.Request;
import org.restlet.data.CharacterSet;
import org.restlet.data.MediaType;
import org.restlet.data.Status;
import org.restlet.representation.Representation;
import org.restlet.representation.StringRepresentation;
import org.restlet.resource.ServerResource;

/**
 *
 * @author alex
 */
public class UserResource extends ServerResource
{
   
   static String ROLE_FACET = "roles";
   AuthDB db;
   XMLRepresentationParser parser = XML.createParser();
   XMLRepresentationParser postParser = XML.createParser();
   String alias;
   String suuid;
   String facet;
   String facetName;
   String facetId;
   /** Creates a new instance of SyncResource */
   public UserResource() {
      setNegotiated(false);
   }

   protected void doInit() {
      db = (AuthDB)getRequest().getAttributes().get(AuthApplication.DB_ATTR);
      parser.addAllowedElement(XML.USER_NAME);
      postParser.addAllowedElement(XML.PASSWORD_NAME);
      postParser.addAllowedElement(XML.ROLE_NAME);
      alias = AuthApplication.getStringAttribute(getRequest(),"user-alias",null);
      suuid = AuthApplication.getStringAttribute(getRequest(),"user-id",null);
      facet = AuthApplication.getStringAttribute(getRequest(),"facet",null);
      facetId = AuthApplication.getStringAttribute(getRequest(),"facet-id",null);
      facetName = AuthApplication.getStringAttribute(getRequest(),"facet-name",null);
   }
   
   public Representation get()
   {
      try {
         User user = fetch();
         if (user!=null) {
            if (facet!=null) {
               if (facet.equals(ROLE_FACET)) {
                  if (facetName==null && facetId==null) {
                     Representation entity = new DBIteratorRepresentation(MediaType.APPLICATION_XML,XML.ROLES_NAME,user.getRoles());
                     entity.setCharacterSet(CharacterSet.UTF_8);
                     return entity;
                  } else {
                     Role role = fetchRole(user);
                     if (role!=null) {
                        Representation entity = new DBObjectRepresentation(MediaType.APPLICATION_XML,role);
                        entity.setCharacterSet(CharacterSet.UTF_8);
                        return entity;
                     } else {
                        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                        return null;
                     }
                  }
               } else {
                  getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                  return null;
               }
            } else {
               Representation entity = new DBObjectRepresentation(MediaType.APPLICATION_XML,user);
               entity.setCharacterSet(CharacterSet.UTF_8);
               return entity;
            }
         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return null;
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value: "+facetId);
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Cannot get user information from database.",ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   public Representation put(Representation entity)
   {
      if (facet!=null) {
         getResponse().setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
         return null;
      }
      if (!XMLRepresentationParser.isXML(entity.getMediaType())) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Non-XML media type for entity body: "+entity.getMediaType().getName());
      }
      Document doc = null;
      
      try {
         DocumentDestination dest = new DocumentDestination();
         parser.parse(entity,dest);
         doc = dest.getDocument();
      } catch (Exception ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("XML parse error: "+ex.getMessage());
      }
      
      try {
         User user = fetch();
         if (user!=null) {
            Element top = doc.getDocumentElement();
            String alias = top.getAttributeValue("alias");
            Element name = top.getFirstElementNamed(XML.NAME_NAME);
            Element email = top.getFirstElementNamed(XML.EMAIL_NAME);
            if (alias!=null && !User.isAlias(alias)) {
               getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
               return new StringRepresentation("The alias '"+alias+"' is not a valid alias.");
            }
            if (alias!=null && !alias.equals(user.getAlias())) {
               // rename
               try {
                  if (!user.changeAlias(alias)) {
                     getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT);
                     return new StringRepresentation("The alias '"+alias+"' is not available.");
                  }
               } catch (SQLException ex) {
                  getContext().getLogger().log(Level.SEVERE,"Database error during while changing alias: "+ex.getMessage(),ex);
                  getResponse().setStatus(Status.CLIENT_ERROR_CONFLICT);
                  return new StringRepresentation("The alias '"+alias+"' is not available.");
               }
            }
            if (name!=null) {
               String value = name.getText();
               if (!value.equals(user.getName())) {
                  // set name
                  user.setName(value);
               }
            } else {
               if (user.getName()!=null) {
                  user.setName(null);
               }
            }
            if (email!=null) {
               String value = email.getText();
               if (!value.equals(user.getEmail())) {
                  // set email
                  user.setEmail(value);
               }
            } else {
               if (user.getEmail()!=null) {
                  user.setEmail(null);
               }
            }
            getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
            return null;
         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return null;
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value specified: "+ex.getMessage());
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Database error during user modify: "+ex.getMessage(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   public Representation post(Representation entity)
   {
      if (!XMLRepresentationParser.isXML(entity.getMediaType())) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Non-XML media type for entity body: "+entity.getMediaType().getName());
      }
      Document doc = null;
      
      try {
         DocumentDestination dest = new DocumentDestination();
         postParser.parse(entity,dest);
         doc = dest.getDocument();
      } catch (Exception ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("XML parse error: "+ex.getMessage());
      }
      
      if (facet!=null && facet.equals(ROLE_FACET)) {
         
      } else {
         
      }
      
      try {
         User user = fetch();
         if (user!=null) {
            Element top = doc.getDocumentElement();
            if (facet!=null && facet.equals(ROLE_FACET)) {
               if (top.getName().equals(XML.ROLE_NAME)) {
                  String sid = top.getAttributeValue("id");
                  String name = top.getAttributeValue("name");
                  Role role = null;
                  if (sid!=null) {
                     role = db.getRole(UUID.fromString(sid));
                  }
                  if (name!=null && role==null) {
                     role = db.getRole(name);
                  }
                  if (role==null) {
                     getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                     return new StringRepresentation("Cannot find role "+name);
                  } else {
                     user.addRole(role);
                     getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
                     return null;
                  }
               } else {
                  getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                  return new StringRepresentation("Element "+top.getName()+" is not allowed.");
               }
            } else if (facet!=null) {
               getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
               return null;
            } else {
               if (top.getName().equals(XML.PASSWORD_NAME)) {
                  String password = top.getText();
                  try {
                     user.setPassword(password);
                     getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
                     return null;
                  } catch (NoSuchAlgorithmException ex) {
                     getContext().getLogger().log(Level.SEVERE,"Error while setting password: "+ex.getMessage(),ex);
                     getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                     return new StringRepresentation("Error encrypting password.");
                  }
               } else {
                  getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
                  return new StringRepresentation("Element "+top.getName()+" is not allowed.");
               }
            }
         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return null;
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value specified: "+ex.getMessage());
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Database error during user delete: "+ex.getMessage(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
   
   protected User fetch()
      throws SQLException,IllegalArgumentException
   {
      User user = null;
      if (alias!=null) {
         user = db.getUser(alias);
      }
      if (suuid!=null) {
         UUID id = UUID.fromString(suuid);
         user = db.getUser(id);
      }
      return user;
   }
   
   protected Role fetchRole(User user)
      throws SQLException,IllegalArgumentException
   {
      Role role = null;
      if (facetName!=null) {
         role = db.getRole(facetName);
      }
      if (facetId!=null) {
         UUID id = UUID.fromString(facetId);
         role = db.getRole(id);
      }
      return role==null ? null : (user.hasRole(role) ? role : null);
   }
   
   public Representation delete() {
      try {
         User user = fetch();
         if (user!=null) {
            if (facet!=null) {
               if (facet.equals(ROLE_FACET)) {
                  if (facetName==null && facetId==null) {
                     getResponse().setStatus(Status.CLIENT_ERROR_METHOD_NOT_ALLOWED);
                     return null;
                  } else {
                     Role role = fetchRole(user);
                     if (role!=null) {
                        if (user.removeRole(role)) {
                           getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
                           return null;
                        } else {
                           getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                           return null;
                        }
                     } else {
                        getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                        return null;
                     }
                  }
               } else {
                  getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
                  return null;
               }
            } else {
               user.delete();
               getResponse().setStatus(Status.SUCCESS_NO_CONTENT);
               return null;
            }
         } else {
            getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND);
            return null;
         }
      } catch (IllegalArgumentException ex) {
         getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST);
         return new StringRepresentation("Bad UUID value specified: "+ex.getMessage());
      } catch (SQLException ex) {
         getContext().getLogger().log(Level.SEVERE,"Database error during user delete: "+ex.getMessage(),ex);
         getResponse().setStatus(Status.SERVER_ERROR_INTERNAL);
         return new StringRepresentation("Exception during processing, see logs.");
      }
   }
  
}
